package com.pearl.jacksoncore.demo.databind.custom;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author TD
 * @version 1.0
 * @date 2024/4/11
 */
public class ListToStringJsonSerializer extends StdSerializer<List> {

    public static final ListToStringJsonSerializer instance = new ListToStringJsonSerializer();

    public ListToStringJsonSerializer() {
        super(String.class, false);
    }

    /**
     * 序列化
     *
     * @param value              被序列化的值
     * @param jsonGenerator      生成器
     * @param serializerProvider 提供者
     * @throws IOException
     */
    @Override
    public void serialize(List value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        // 空集合值写入 “”
        if (CollUtil.isEmpty(value)) {
            jsonGenerator.writeString("");
        } else {
            // 写入转为“,”拼接的字符串
            String commaString = CollUtil.join(value, StrUtil.COMMA);
            jsonGenerator.writeString(commaString);
        }
    }

    public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException {
        this.visitStringFormat(visitor, typeHint);
    }
}
